import {messages} from "share/common";
import React from 'react'
import { connect } from 'react-redux'
import ResizeTable from 'components/resize-table'
import config from 'config'
import { Button, Badge } from 'antd';
import httpFetch from 'share/httpFetch'
import {setSetOfBooks} from 'actions/cache';
import SearchArea from 'components/search-area'
import SlideFrame from 'components/slide-frame'
import NewSetOfBooks from 'containers/finance-setting/set-of-books/new-set-of-books'
import sobService from 'containers/finance-setting/set-of-books/set-of-books.service';
import menuRoute from "routes/menuRoute";

class SetOfBooks extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      loading: true,
      data: [],
      page: 0,
      pageSize: 10,
      columns: [
        {title: messages('finance-setting.key116'/*账套代码*/), dataIndex: "setOfBooksCode"},
        {title: messages('finance-setting.key119'/*账套名称*/), dataIndex: "setOfBooksName"},
        {title: messages('finance-setting.key118'/*会计期代码*/), dataIndex: "periodSetCode"},
        {title: messages('finance-setting.key4'/*本位币*/), dataIndex: "functionalCurrencyCode"},
        {title: messages('finance-setting.key121'/*科目表代码*/), dataIndex: "accountSetCode"},
        {title: messages("common.column.status"), dataIndex: 'enabled', render: enabled => (
          <Badge status={enabled ? 'success' : 'error'} text={enabled ? messages('common.status.enable') : messages('common.status.disable')} />)},
        {title: messages('common.operation')/*操作*/, dataIndex: 'operator', render: (value,record) => {
          return (<div>
            <a onClick={e => this.handleRowClick(e,record)} disabled={!props.tenantMode}>{messages('common.edit')/*编辑*/}</a>
            <span className="ant-divider"/>
            <a onClick={e => this.handleSetting(e,record)} disabled={!props.tenantMode}>{messages('finance-setting.key158')/*帐套设置*/}</a>
          </div>)
          }}
      ],
      pagination: {
        total: 0
      },
      searchForm: [
        {type: 'input', id: 'setOfBooksCode', label: messages('finance-setting.key116'/*账套代码*/)},
        {type: 'input', id: 'setOfBooksName', label: messages('finance-setting.key119'/*账套名称*/)}
      ],
      searchParams: {
        setOfBooksCode: '',
        setOfBooksName: ''
      },
      showSlideFrame: false,
      nowSetOfBooks: {},
      setOfBookSetting: menuRoute.getRouteItem('set-of-book-setting')
    };
  }

  componentWillMount(){
    this.props.dispatch(setSetOfBooks({}));
    this.getList();
  }

  //得到列表数据
  getList(){
    this.setState({ loading: true });
    let params = this.state.searchParams;
    params.page = this.state.page;
    params.size = this.state.pageSize;
    let url = `${config.baseUrl}/api/setOfBooks/query/dto`;
    return httpFetch.get(url, params).then((response)=>{
      response.data.map((item)=>{
        item.key = item.id;
      });
      this.setState({
        data: response.data,
        loading: false,
        pagination: {
          total: Number(response.headers['x-total-count']),
          onChange: this.onChangePager,
          current: this.state.page + 1
        }
      })
    });
  }

  //分页点击
  onChangePager = (page) => {
    if(page - 1 !== this.state.page)
      this.setState({
        page: page - 1,
        loading: true
      }, ()=>{
        this.getList();
      })
  };

  search = (result) => {
    this.setState({
      page: 0,
      searchParams: Object.assign({}, this.state.searchParams, result)
    }, ()=>{
      this.getList();
    })
  };

  clear = () => {
    this.setState({
      searchParams: {
        setOfBooksCode: '',
        setOfBooksName: ''
      }
    })
  };

  handleNew = () => {
    this.setState({ nowSetOfBooks: {}, showSlideFrame: true })
  };

  handleRowClick = (e,record) => {
    e.stopPropagation();
    sobService.getSobDetail(record.setOfBooksId)
      .then(res=>{
        this.setState({ nowSetOfBooks: res.data }, () => {
          this.setState({ showSlideFrame: true });
        })
      })
  };

  handleSetting = (e,record) => {
    const { setOfBookSetting } = this.state;
    e.stopPropagation();
    this.props.dispatch(setSetOfBooks(record));
    this.context.router.push(setOfBookSetting.url);
  };

  handleCloseSlide = (success) => {
    success && this.getList();
    this.setState({showSlideFrame : false});
  };

  render(){
    const { columns, data, loading,  pagination, searchForm, showSlideFrame, nowSetOfBooks } = this.state;

    return (
      <div>
        <h3 className="header-title">{messages('finance-setting.key123'/*账套定义*/)}</h3>
        <SearchArea
          searchForm={searchForm}
          submitHandle={this.search}
          clearHandle={this.clear}/>

        <div className="table-header">
          <div className="table-header-title">{messages('common.total', {total: pagination.total + ''})}</div> {/* 共total条数据 */}
          <div className="table-header-buttons">
            <Button type="primary"
                    disabled={!this.props.tenantMode}
                    onClick={this.handleNew}>{messages('common.create')}</Button> {/* 新建 */}
          </div>
        </div>
        <ResizeTable
          columns={columns}
          dataSource={data}
          pagination={pagination}
          loading={loading}
          rowKey="setOfBooksId"
          bordered
          size="middle"/>

        <SlideFrame content={NewSetOfBooks}
                    title={nowSetOfBooks.setOfBooksId ? messages('finance-setting.key124'/*编辑账套*/) : messages('finance-setting.key125'/*新建账套*/)}
                    show={showSlideFrame}
                    onClose={() => this.setState({showSlideFrame : false})}
                    afterClose={this.handleCloseSlide}
                    params={{nowSetOfBooks, showSlideFrame}}/>

      </div>
    )
  }

}

SetOfBooks.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    tenantMode: state.main.tenantMode,
  }
}
export default connect(mapStateToProps)(SetOfBooks);
